package com.sleepfish.web.controller.power;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.sleepfish.system.domain.SysPost;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.sleepfish.common.annotation.Log;
import com.sleepfish.common.constant.UserConstants;
import com.sleepfish.common.core.controller.BaseController;
import com.sleepfish.common.core.domain.AjaxResult;
import com.sleepfish.common.core.domain.entity.SysRole;
import com.sleepfish.common.core.domain.entity.SysUser;
import com.sleepfish.common.core.page.TableDataInfo;
import com.sleepfish.common.enums.BusinessType;
import com.sleepfish.common.utils.SecurityUtils;
import com.sleepfish.common.utils.StringUtils;
import com.sleepfish.common.utils.poi.ExcelUtil;
import com.sleepfish.system.service.ISysPostService;
import com.sleepfish.system.service.ISysRoleService;
import com.sleepfish.system.service.ISysUserService;

/**
 * 用户信息
 * 
 * @author xiaochao
 */
@Api(tags = "用户信息")
@RestController
@RequestMapping("/power/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;


    @ApiOperation(value = "获得用户的列表")
    @PreAuthorize("@ss.hasPermi('power:user:list')")
    @GetMapping("/list")
    public TableDataInfo listUser(SysUser sysUser)
    {
        startPage();
        List<SysUser> listUser = sysUserService.selectUserList(sysUser);
        return getDataTable(listUser);
    }

    @ApiOperation(value = "获取用户精简信息列表")
    @PreAuthorize("@ss.hasPermi('power:user:list')")
    @GetMapping("/list-all-simple")
    public AjaxResult getSimpleUsers()
    {
        SysUser user =new SysUser();
        user.setStatus("0");
        List<SysUser> list = sysUserService.selectUserList(user);
        return AjaxResult.success(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('power:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = sysUserService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @ApiOperation(value = "导入信息")
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('power:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = sysUserService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }


    @ApiOperation(value = "根据用户编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('power:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(
            @ApiParam(name = "userId", value = "用户ID", required = true)
            @PathVariable(value = "userId", required = false) Long userId)
    {
        sysUserService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, sysUserService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }


    @ApiOperation(value = "新增用户")
    @PreAuthorize("@ss.hasPermi('power:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(sysUserService.insertUser(user));
    }

    @ApiOperation(value = "修改用户")
    @PreAuthorize("@ss.hasPermi('power:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        sysUserService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(sysUserService.updateUser(user));
    }

    @ApiOperation(value = "删除用户")
    @PreAuthorize("@ss.hasPermi('power:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(
            @ApiParam(name = "userIds", value = "用户ID数组", required = true)
            @PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(sysUserService.deleteUserByIds(userIds));
    }


    @ApiOperation(value = "重置密码")
    @PreAuthorize("@ss.hasPermi('power:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        sysUserService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(sysUserService.resetPwd(user));
    }


    @ApiOperation(value = "状态修改")
    @PreAuthorize("@ss.hasPermi('power:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        sysUserService.checkUserAllowed(user);
        user.setUpdateBy(getUsername());
        return toAjax(sysUserService.updateUserStatus(user));
    }

    @ApiOperation(value = "根据用户编号获取授权角色")
    @PreAuthorize("@ss.hasPermi('power:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(
            @ApiParam(name = "userId", value = "用户ID", required = true)
            @PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = sysUserService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }


    @ApiOperation(value = "用户授权角色")
    @PreAuthorize("@ss.hasPermi('power:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(
            @ApiParam(name = "userId", value = "用户ID", required = true)
            @RequestParam Long userId,
            @ApiParam(name = "roleIds", value = "角色ID数组", required = true)
            @RequestParam Long[] roleIds)
    {
        sysUserService.insertUserAuth(userId, roleIds);
        return success();
    }
}
